<template>
	<el-dialog v-model="state.visible" draggable :close-on-click-modal="false" width="500px">
		<template #header>
			<div style="color: #fff">
				<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>
				<span> 设置用户类型 </span>
			</div>
		</template>
		<el-form style="min-height: 100px;" :model="state.form" ref="formRef" label-width="auto">
			<el-form-item label="用户类型" prop="type" :rules="[{ required: true, message: '请选择用户类型', trigger: 'blur' }]">
				<el-select v-model="state.form.type" placeholder="请选择">
					<el-option v-for="item in state.typeList"
		      :key="item.value"
		      :label="item.typeName"
		      :value="item.value"></el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="cancel">取 消</el-button>
				<el-button :loading="state.loading" type="primary" @click="submit">提 交</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { ElNotification } from 'element-plus'
import {getUserTypeList, getUserType, setUserType} from "/@/api/system/user"

const emits = defineEmits(['reload']);
const formRef = ref();

const state = reactive({
	visible: false,
	loading: false,

	form: {
		type: '',
		userId: ''
	},

	typeList: []
});

onMounted(() => {
	getUserTypeList().then(res => {
		state.typeList = res.data.result;
	})
})

// 打开弹窗
const open = (id) => {
	state.form.userId = id;
	state.visible = true;

	getType();
};

// 获取用户当前类型
const getType = () => {
	getUserType(state.form.userId).then(res => {
		state.form.type = res.data.result;
	})
}

// 关闭弹窗
const closeDialog = () => {
	emits('reload');
	state.visible = false;
};

// 取消
const cancel = () => {
	state.visible = false;
};

// 提交
const submit = () => {
	formRef.value.validate(async (valid) => {
		if (!valid) return;
		state.loading = true;
		setUserType(state.form.type, state.form.userId).then(res => {
			if(res.data.code == 200) {
				ElNotification({
			    title: '提示',
			    message: '操作成功',
			    type: 'success',
			  })
				closeDialog();
			}
		}).finally(() => {
			state.loading = false;
		})
	});
};


// 导出对象
defineExpose({ open });
</script>
